import { getStuRows, delStuRows, addStuRows, saveSelectStuRows } from '@/api/list.js';
import { ElMessage } from 'element-plus';
import { defineStore } from 'pinia';

export const useRecordStore = defineStore('record', {
  state: () => ({
    records: [], // 原始记录列表
    paginatedRecords: [], // 全局分页数据（home页面使用）
    total: 0,    // 总记录数（未筛选的总数）
    loading: false, // 加载状态
    selectedRecords: [], // 选中的记录列表
    semesterid: '',  //学期id
    
    // 使用对象存储不同页面的筛选状态
    filters: {
      listPage: {
        filterType: 'all', // list页面的筛选类型
        paginatedRecords: [], // list页面的分页数据
        filteredTotal: 0 // list页面筛选后的总数
      }
    }
  }),
  getters: {
    approvedRecords() {
      return this.records.filter(record => record.status === '已审核');
    },
    pendingRecords() {
      return this.records.filter(record => record.status === '待审核');
    },
    // 为list页面添加专门的筛选后记录getter
    listPageFilteredRecords() {
      if (this.filters.listPage.filterType === 'all') {
        return this.records;
      }
      return this.records.filter(record => record.PARENT_NAME === this.filters.listPage.filterType);
    }
  },
  actions: {
    // 设置当前选择的学期id
    setSemesterId(id) {
      this.semesterid = id;
    },
    
    // 为list页面添加专门的分页方法
    setListPagePaginatedRecords(page, pageSize) {
      const filteredRecords = this.listPageFilteredRecords;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      this.filters.listPage.paginatedRecords = filteredRecords.slice(startIndex, endIndex);
      this.filters.listPage.filteredTotal = filteredRecords.length;
    },
    
    // 为list页面添加专门的筛选方法
    // 修改setListPageFilterType方法，让它接受当前页码和每页大小参数
    setListPageFilterType(type, page = 1, pageSize = 5) {
      this.filters.listPage.filterType = type;
      // 筛选后重新分页（使用传入的页码和每页大小）
      this.setListPagePaginatedRecords(page, pageSize);
    },
    
    // 修改fetchRecords方法，让它接受页码和每页大小参数
    async fetchRecords(year, page = 1, pageSize = 5) {
      this.loading = true;
      try {
        let result = await getStuRows();
        let  res = result.filter(record => record.SEMESTER_ID == year);
        if (res && Array.isArray(res)) {
          this.records = res;
          this.total = res.length;
          // 为list页面重新计算筛选和分页
          this.setListPagePaginatedRecords(page, pageSize);
          // 同时更新全局分页数据（供home页面使用）
          this.setPaginatedRecords(page, pageSize);
        } else {
          ElMessage.error('获取学生记录失败，数据格式错误');
          this.records = [];
          this.paginatedRecords = [];
          this.total = 0;
          this.filters.listPage.paginatedRecords = [];
          this.filters.listPage.filteredTotal = 0;
        }
      } catch (error) {
        ElMessage.error('获取学生记录失败，请稍后重试')
        this.records = [];
        this.paginatedRecords = [];
        this.total = 0;
        this.filters.listPage.paginatedRecords = [];
        this.filters.listPage.filteredTotal = 0;
      } finally {
        this.loading = false;
      }
    },
    
    // 保留原有的setPaginatedRecords方法（供home页面使用）
    setPaginatedRecords(page, pageSize) {
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      this.paginatedRecords = this.records.slice(startIndex, endIndex);
    },
    
    // 删除成长记录
    async deleteRecord(id) {
      try {
        const res = await delStuRows(id);
        if (res.code > 0) {
          ElMessage.success('删除成功');
          this.records = this.records.filter(record => record.RECORD_ID !== id);
          this.total = this.records.length;
          // 重新分页
          this.setPaginatedRecords(1, 5);
          // 同时更新list页面的分页
          this.setListPagePaginatedRecords(1, 5);
        } else {
          ElMessage.error('删除失败');
        }
      } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
      }
    },
    
    // 添加成长记录
    async addRecord(data) {
      try {
        const res = await addStuRows(data);
        console.log(res);
        if (res.code > 0) {
          ElMessage.success('添加成功');
          await this.fetchRecords(); // 重新获取列表
        } else {
          ElMessage.error('添加失败');
        }
      } catch (error) {
        ElMessage.error('添加失败，请稍后重试');
      }
    },

    //保存遴选记录
    async saveSelectedRecordsData(ids) {
      try {
        const res = await saveSelectStuRows(ids);
        if (res.code > 0) {
          ElMessage.success('保存成功');
        } else {
          ElMessage.error('保存失败');
        }
      } catch (error) {
        ElMessage.error('保存失败，请稍后重试');
      }
    }
  }
});